import type { ZhiHuQuestionPageTypeResult } from './types'
import { PageRoute } from '../../../abstract/page_route'
import { ZhiHuQuestionPageType } from './types'

export class ZhiHuQuestionPage extends PageRoute {
  readonly name: string = 'ZhiHuQuestionPage'
  private static instance: ZhiHuQuestionPage
  get pageType(): ZhiHuQuestionPageType | 'default' {
    return this.getCurrentPageMeta().type
  }

  /**
   * 获取单例实例
   */
  public static getInstance(): ZhiHuQuestionPage {
    if (!ZhiHuQuestionPage.instance) {
      ZhiHuQuestionPage.instance = new ZhiHuQuestionPage()
    }
    return ZhiHuQuestionPage.instance
  }

  /**
   * 获取当前页面类型
   */
  public getCurrentPageMeta(): ZhiHuQuestionPageTypeResult {
    const url = this.getCurrentUrl()
    const path = new URL(url).pathname

    // 404 页面检测
    const notFoundResult = this.detectNotFoundPage()
    if (notFoundResult)
      return notFoundResult

    // 基础页面检测
    const pageResult = this.detectPages(path)
    if (pageResult)
      return pageResult

    // 未定义页面
    return { type: ZhiHuQuestionPageType.Undefined }
  }

  /**
   * 检测 404 页面
   */
  private detectNotFoundPage(): ZhiHuQuestionPageTypeResult | null {
    const pageNotFoundRules = [
      /404.*Not Found/i, // 不区分大小写
      /页面不存在/,
    ]

    if (pageNotFoundRules.some(regex => regex.test(document.title))) {
      return { type: ZhiHuQuestionPageType.NotFound }
    }

    return null
  }

  /**
   * 检测其他功能页面
   */
  private detectPages(basePath: string): ZhiHuQuestionPageTypeResult | null {
    const pageDetectors: Array<[RegExp, (...args: any[]) => ZhiHuQuestionPageTypeResult]> = [
      [/^\/question\/\d+\/answer\/\d+$/, () => {
        return { type: ZhiHuQuestionPageType.Answer }
      }],
      [/^\/question\/\d+$/, () => {
        return { type: ZhiHuQuestionPageType.Question }
      }],
    ]

    for (const [regex, handler] of pageDetectors) {
      const match = basePath.match(regex)
      if (match) {
        return handler(match)
      }
    }

    return null
  }
}
